package com.vincent.sms;

import android.Manifest;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Telephony;
import android.telephony.SmsManager;

import androidx.core.content.ContextCompat;

import java.util.ArrayList;

/**
 * projectName:          Sms
 * packageName:          com.vincent.sms
 * className:            SmsSender
 * author:               Luoxiang
 * time:                 2025/6/29	10:42
 * desc:                 TODO
 * <p>
 * svnVersion:
 * upDateAuthor:         a
 * upDate:               2025/6/29
 * upDateDesc:           TODO
 */
public class SmsSender {
    public static void sendSms(Context context, String phoneNumber, String message) {
        // 检查是否为默认短信应用
        if (!isDefaultSmsApp(context)) {
            // 提示用户设置为默认应用
            showSetDefaultDialog(context);
            return;
        }

        // 发送短信
        SmsManager smsManager = SmsManager.getDefault();
        ArrayList<String> parts = smsManager.divideMessage(message);

        ArrayList<PendingIntent> sentIntents = new ArrayList<>();
        for (int i = 0; i < parts.size(); i++) {
            sentIntents.add(PendingIntent.getBroadcast(
                    context, 0, new Intent("SMS_SENT"), 0));
        }

        smsManager.sendMultipartTextMessage(
                phoneNumber, null, parts, sentIntents, null);

        // 保存到发件箱
        saveToSentBox(context, phoneNumber, message);
    }

    private static boolean isDefaultSmsApp(Context context) {
        String myPackageName = context.getPackageName();
        String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(context);
        return myPackageName.equals(defaultSmsApp);
    }

    private static void showSetDefaultDialog(final Context context) {
        new AlertDialog.Builder(context)
                .setTitle("设置为默认短信应用")
                .setMessage("需要将此应用设置为默认短信应用才能发送短信")
                .setPositiveButton("设置", (dialog, which) -> {
                    Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                    intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, context.getPackageName());
                    context.startActivity(intent);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private static void saveToSentBox(Context context, String address, String body) {
        ContentValues values = new ContentValues();
        values.put("address", address);
        values.put("body", body);
        values.put("date", System.currentTimeMillis());
        values.put("read", 1); // 已读
        values.put("type", 2); // 2表示发件箱

        context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
    }
}
